﻿using System.Data;
using Wen.Core.Extensions;
using WenAntdUI.Extensions;
using WenAntdUI.Helps;

namespace WenAntdUI.Pages.Components
{
    public partial class UserRoleSelectForm : WenForm
    {
        private readonly IFreeSql fsql;

        public UserRoleSelectForm(IFreeSql fsql)
        {
            this.fsql = fsql;
            this.StartPosition = FormStartPosition.CenterParent;
            InitializeComponent();
        }

        private string UserName { get; set; }

        public void SetUserRole(string userName)
        {
            this.UserName = userName;
            this.Text += " " + userName;
            var userRoles = fsql.Select<SysUserRole>().Where(t => t.UserName == userName).ToList();

            var roles = fsql.Select<SysRole>().ToList();

            this.tree1.Items.Clear();

            foreach (var role in roles)
            {
                this.tree1.Items.Add(new AntdUI.TreeItem()
                {
                    Name = role.RoleName,
                    Text = role.Description ?? role.RoleName,
                    SubTitle = role.RoleName,
                    Checked = userRoles.Exists(t => t.RoleName == role.RoleName)
                });
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            var tss = tree1.GetCheckeds();

            var userroles = tss.Select(t => new SysUserRole() { RoleName = t.Name, UserName = UserName });

            fsql.Delete<SysUserRole>().Where(a => a.UserName == UserName).ExecuteEffects();
            fsql.Insert<SysUserRole>().AppendData(userroles).ExecuteEffects();

            Msgbox.ShowSuccess("保存成功");
            this.Close();
        }
    }
}
